<?php

namespace App\Modules\Admin\Services\Water\Member;

use App\Exceptions\Exception;

use App\Modules\Admin\Entities\Member\UserScoreModel;
use App\Modules\Admin\Entities\Member\UsersModel;
use App\Modules\Admin\Entities\Water\WaterDeviceModel;
use App\Modules\Admin\Entities\Water\WaterWithUserModel;
use App\Modules\Admin\Services\BaseService;
use Illuminate\Support\Facades\DB;

class UsersService extends BaseService
{
    public function __construct(UsersModel $userModel)
    {
        $this->model = $userModel;
        $this->UserScoreModel = new UserScoreModel;
        $this->modelUserWithApparatuses = new WaterWithUserModel();
    }

    public function lists(array $params) : array
    {
       $params['where_callback'] = function($query) use ($params){
            $request = request();
            // 按照名称进行搜索
            if (!empty($search = $request->input('search', ''))){
                $query->where('nickname', 'LIKE', '%' . trim($search) . '%');
            }
            if (!empty($id = $request->input('id', ''))){
                $query->where('id', $id);
            }
            if (!empty($nickname = $request->input('nickname', ''))){
                $query->where('nickname', $nickname)->orWhere('mobile', trim($nickname) );;
            }
            if (!empty($flag = $request->input('flag', ''))){
                $query->where('flag', $flag);
            }
            if (!empty($role = $request->input('role', ''))){
                $query->where('water_role', $role);
            }
            if (!empty($search = $request->input('search', ''))){
                $query->where('nickname', 'LIKE', '%' . trim($search) . '%');
            }
        };

        return parent::lists($params); // TODO: Change the autogenerated stub
    }
    public function getSelectLists($request)
    {
        return $this->model->where(function($query) use ($request){
            $search = $request->input('mobile', '');
            // 可以按照名称进行搜索
            if (!empty($search)){
                $query->where('company_name', 'LIKE', '%' . trim($search) . '%');
            }
            $water_role = $request->input('water_role', '');
            if (!empty($water_role)){
                $query->where('water_role', $water_role);
            }
        })->orderBy($this->model->getKeyName(), 'ASC')->get(['id','nickname','mobile'])->toArray();
    }

    public function getSelectListsUnusual()
    {
        return $this->model->get(['id','nickname']);
    }

    public function create(array $params)
    {
        unset($params['id']);
        $password = $params['password'];
        if ($password){
            $salt=rand_str();
            $hashedPassword = md5($password.$salt);
            $params['password'] = $hashedPassword;
            $params['pw'] = $password;
            $params['salt'] = $salt;
        }

        DB::beginTransaction();
        try{
            parent::create($params); // TODO: Change the autogenerated stub
            DB::commit();
            return true;
        }catch (Exception $e){
            DB::rollBack();
            throw new Exception($e->getMessage());
        }
    }
    public function update(array $params)
    {
        $password = $params['password']??'';
        if ($password){
            $salt=rand_str();
            $hashedPassword = md5($password.$salt);
            $params['password'] = $hashedPassword;
            $params['pw'] = $password;
            $params['salt'] = $salt;
        }
        DB::beginTransaction();
        try{
            parent::update($params); // TODO: Change the autogenerated stub
            DB::commit();
            return true;
        }catch (Exception $e){
            DB::rollBack();
            throw new Exception($e->getMessage());
        }
    }
    public function detail($request){
        $id = $request->input('id', 0);
        $user = $this->model->where(['id'=>$id])->first(['username','nickname', 'mobile', 'water_role']);

        $water_role = $user['water_role'];
        $UserWithApparatuses =  $this->modelUserWithApparatuses
            ->where(['user_id'=>$id,'is_delete'=>0,'water_role'=>$water_role])
            ->get(['apparatuses_id as id'])->toArray();


        $water_list= WaterDeviceModel::getInstance()
            ->getSelectListsById(array_column($UserWithApparatuses,'id'));

        $user_list['user'] = $user;
        $user_list['user_with_water'] = $UserWithApparatuses;
        $user_list['water_list'] = $water_list;

        return $user_list;
    }
    public function getUsersWaterLists(array $params)
    {

        $user_id = $params['id'];
        $res = $this->model->with(['water_device_info'])->where(['user_id'=>$user_id])->get();
        return $res;
    }
    public function getUsersIntegraDetailLists(array $params)
    {
        $user_id = $params['uid'];
        $user_id = $params['uid'];

        $this->UserScoreModel->with(['water_device_info'])->where(['user_id'=>$user_id])
            ->orderBy($this->model->getKeyName(), 'ASC')
            ->limit(100)->get()->toArray();


        $res = $this->model->with(['water_device_info'])->where(['user_id'=>$user_id])->get();
        return $res;
    }
    public function updateUsersWater(array $params)
    {
        $user_id = $params['user_id'];
        $water_role = $params['water_role'];
        $waterIds = $params['waterIds']??[];

        DB::beginTransaction();
        try{
            $this->modelUserWithApparatuses->where(['user_id'=>$params['user_id'],'water_role'=>$params['water_role']])->update(['is_delete'=>1]);
            foreach ($waterIds as $waterId){
                $this->modelUserWithApparatuses->create([
                    'user_id'=>$user_id,
                    'water_role'=>$water_role,
                    'water_id'=>$waterId,
                ]);
            }
            DB::commit();
            return true;
        }catch (Exception $e){
            DB::rollBack();
            throw new Exception($e->getMessage());
        }
    }
    /**
     * 用户 权限
     * @param $param
     * @return void
     */
    public function rolesUser($param){
        DB::beginTransaction();
        try{
            parent::update($param); // TODO: Change the autogenerated stub
            DB::commit();
            return true;
        }catch (Exception $e){
            DB::rollBack();
            throw new Exception($e->getMessage());
        }
    }


}
